package com.tiny.interceptor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.tiny.model.SysLog;
import com.tiny.model.User;
import com.tiny.thread.ThreadSysLog;
import com.tiny.tools.ToolWeb;

/**
 * 简单的未登录拦截
 * 
 */
public class ManagerInterceptor implements Interceptor {
	
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public void intercept(Invocation ai) {
		Controller controller = ai.getController();
		// 获取session
		HttpSession session = controller.getSession();
		User loginUser = (User)session.getAttribute("user");

		// session为空
		if (loginUser!=null) {
			//记录操作日志
			SysLog reqSysLog = new SysLog();

			reqSysLog.set("starttime", sdf.format(new Date()));
			reqSysLog.set("username", loginUser.getStr("username"));
			reqSysLog.set("ip", ToolWeb.getIpAddr(controller.getRequest()));
			reqSysLog.set("controller", ai.getActionKey());
			reqSysLog.set("method", ai.getMethodName());
			
			StringBuilder sb = new StringBuilder("");
			String urlParas = controller.getPara();
			if (urlParas != null) {
				sb.append("UrlPara     : ").append(urlParas).append(" ");
			}
			// print all parameters
			HttpServletRequest request = controller.getRequest();
			Enumeration<String> e = request.getParameterNames();
			if (e.hasMoreElements()) {
				sb.append("Parameter   : ");
				while (e.hasMoreElements()) {
					String name = e.nextElement();
					String[] values = request.getParameterValues(name);
					if (values.length == 1) {
						sb.append(name).append("=").append(values[0]);
					}
					else {
						sb.append(name).append("[]={");
						for (int i=0; i<values.length; i++) {
							if (i > 0)
								sb.append(",");
							sb.append(values[i]);
						}
						sb.append("}");
					}
					sb.append("  ");
				}
			}
			reqSysLog.set("parameter", sb.toString());
			
			ThreadSysLog.add(reqSysLog);
		}
		
		ai.invoke();// 注意 一定要执行此方法
	}
}
